package data

import (
	"github.com/go-kratos/kratos/v2/log"
	"goods/internal/biz"
	"context"
)

var _ biz.ProductRepo = (*productRepo)(nil)

type productRepo struct {
	data *Data
	log  *log.Helper
}

// NewArticleRepo .
func NewProductRepo(data *Data, logger log.Logger) biz.ProductRepo {
	return &productRepo{
		data: data,
		log:  log.NewHelper(logger),
	}
}

func (r *productRepo) CreateProduct(ctx context.Context, b *biz.Product) (*biz.Product, error) {
	result := r.data.db.WithContext(ctx).Create(&b)
	return &biz.Product{
		ProductId: b.ProductId,
	}, result.Error
}

func (r *productRepo) GetProduct(ctx context.Context, productId int64) (*biz.Product, error) {
	p := biz.Product{}
	result := r.data.db.WithContext(ctx).First(&p, productId)
	return &biz.Product{
		ProductId: p.ProductId,
	}, result.Error
}

func (r *productRepo) UpdateProduct(ctx context.Context, productId int64, b *biz.Product) (*biz.Product, error) {
	p := biz.Product{}
	result := r.data.db.WithContext(ctx).First(&p, productId)
	if result.Error != nil {
		return nil, result.Error
	}
	p.Name = b.Name
	result = r.data.db.WithContext(ctx).Save(&p)
	if result.Error != nil {
		return nil, result.Error
	}
	return &biz.Product{
		ProductId: p.ProductId,
	}, nil
}

func (r *productRepo) ListProduct(ctx context.Context, pageNum, pageSize int64) ([]*biz.Product, error) {
	var os []biz.Product
	result := r.data.db.WithContext(ctx).
		Limit(int(pageSize)).
		Offset(int((pageNum - 1) * pageSize)).
		Find(&os)
	if result.Error != nil {
		return nil, result.Error
	}
	rv := make([]*biz.Product, 0)
	for _, o := range os {
		rv = append(rv, &biz.Product{
			ProductId: o.ProductId,
		})
	}
	return rv, nil
}

func (r *productRepo) DeleteProduct(ctx context.Context, productId int64) error {
	p := biz.Product{}
	err := r.data.db.WithContext(ctx).Delete(&p, productId).Error
	return err
}